import json
from json import *
from urllib.parse import urlencode
import os
import requests


##请求地址
def get_page():
    data = {
        "sort": "time_desc",
        "pageIndex": 1,
        "pageSize": 50,
        "nodeId": "21089"
    }
    url = "http://pic.gamersky.com/home/getimagesindex?"+urlencode(data)
    print("访问地址:" + url)
    page = send_request(url, "text")

    js1 = json.loads(page)
    js2 = json.loads(js1)
    body = js2.get("body")
    #jsondata:{"generalId":"930759","sort":"hot_desc","gameId":"0","tagId":"0","index":"1","nodeId":0,"Id":"41678"}
    pic_list = []
    for body_len in range(len(body)):
        general_id = body[body_len].get("generalId")
        pic_id = body[body_len].get("id")
        path = body[body_len].get("path")
        title = body[body_len].get("title")
        print(body[body_len])
        req = {
            "general_id": general_id,
            "id": pic_id,
            "path": path,
            "title": title
        }
        pic_list.append(req)
    return pic_list


def get_pic_detail(pic_list):
    all_list = []
    for i in range(len(pic_list)):
        pic_dict = {}
        pic_url_list = []
        gid = pic_list[i].get("general_id")
        pic_id = pic_list[i].get("id")
        title = pic_list[i].get("title")

        for index in range(3):
            req = {
                "generalId": gid,
                "Id": pic_id-index,
                "sort": "hot_desc",
                "gameId": "0",
                "index": index+1
            }
            j_req = JSONEncoder().encode(req)
            url = "http://pic.gamersky.com/home/getsingleimage?jsondata=" + j_req
            print("访问地址1:"+url)
            res = send_request(url, "text")
            pic_res = json.loads(json.loads(res))
            pic_url = pic_res.get("body").get("originImg")
            print(pic_url)
            #total_Count = pic_res.get("totalCount")

            pic_url_list.append(pic_url)
            pic_dict["picurl"] = pic_url_list
            pic_dict["title"] = title
            all_list.append(pic_dict)
    return all_list


def down_load(all_list):
    for i in range(len(all_list)):
        title = all_list[i].get("title")
        file_path = "d://python_image/"+title+"/"
        if not os.path.exists(file_path):
            os.makedirs(file_path)

        pic_list = all_list[i].get("picurl")
        for j in range(len(pic_list)):
            lib = file_path + str(j) + ".jpg"
            file = open(lib, "wb")
            file.write(send_request(pic_list[j], 'content'))
            file.close()


def send_request(url, types):
    if types is None:
        types = "text"
    response = requests.get(url)
    try:
        if response.status_code == 200:
            if types == "text":
                return response.text
            return response.content
        else:
            print("链接失败")
    except IOError:
        print("链接错误")


if __name__ == "__main__":
    down_load(get_pic_detail(get_page()))